// Module dependencies.
var express = require('express'),
  path = require('path'),
  conf = require('smart-conf')(),
  security = require('smart-security'),
  authentication = security.layers.authentication,
  requireRight = security.layers.authorization.requireRight,
  logcontroller = require('./controllers/logcontroller'),
  cors = require('connect-cors'),
  logger = require('smart-logger')(module),
  errorHandler = require('smart-errors');

  express.bodyParser.parse["text/plain"]=function(req, option, next){
    var buf = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk){ buf += chunk });
    req.on('end', function(){
      try {
        req.body = buf.length
        ? buf
        : "";
        next();
      } catch (err){
        err.status = 400;
        next(err);
      }
    });
  };

  var setup = function setup () {
    // Create a new Express server
    var app = express.createServer();

    // ### Middlewares configuration
    // Configure middlewares; each middleware is executed on the request in the order below
    app.configure(function() {
      app.use(express.methodOverride())

      .use(express.bodyParser())
      .use(function (req, res, next) {
        res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Expires', 'Thu, 01 Dec 1994 16:00:00 GMT');
        res.setHeader('Max-Age', '0');
        res.setHeader('Pragma', 'no-cache');
        next();
      })

      .use(express.favicon(__dirname + '/public/favicon.ico'))

      .use(app.router)

      .use(function(req, res, next) {
        return next(new Error('ENOTFOUND page not found.'));
      });
    });

    app.configure('dev', function(){
      // `app.error` equivalent of `app.use(express.errorHandler())`
      app.error(errorHandler({
        stack: true,
        message: true
      },__dirname));
    });

    app.configure('development', function(){
      // `app.error` equivalent of `app.use(express.errorHandler())`
      app.error(errorHandler({
        stack: true,
        message: true
      }, __dirname));
    });

    app.configure('test', function(){
      // `app.error` equivalent of `app.use(express.errorHandler())`
      app.error(errorHandler({
        stack: true,
        message: true
      },__dirname));
    });


    app.configure('qlf', function() {
      app.error(errorHandler({},__dirname));
    });

    app.configure('production', function() {
      app.error(errorHandler({},__dirnamei));
    });

    // ### Routes configuration

    // Consult a dataStream
    app.post('/inputs/:id', logcontroller.add);

    return app;
  };

  exports.setup = setup;

  exports.start = function start (port, host, readyCallback) {
    var app;
    console.log("starting the server! ");
    if(typeof port === "function") {
      readyCallback = port;
      host = conf.get("logs-server:server:host");
      port = conf.get("logs-server:server:port");
    }
    logger.debug("Re Start smart-logs-server on " + host + ":" + port);
    console.log(" LOG Start smart-logs-server on " + host + ":" + port);
    app = setup();
    app.listen(port, host, readyCallback);
    return app;
  };

